// $Id: CheckoutHandler.java 51 2011-10-21 16:53:27Z huijzer@gmail.com $
package lime.browser.command;

import lime.browser.view.NavigatorView;
import lime.common.LimeException;
import lime.common.UIUtils;
import lime.model.Document;
import lime.service.RepositoryService;
import lime.service.SpringApplicationContext;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.IDfId;
import com.documentum.operations.IDfCheckoutOperation;

public class CheckoutHandler extends AbstractHandler {

	private RepositoryService repositoryService;

	public CheckoutHandler() {
		super();
		repositoryService = (RepositoryService) SpringApplicationContext.getBean("repositoryService");
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object element = structuredSelection.getFirstElement();
			if (element != null && element instanceof Document) {
				Document document = (Document) element;
				IDfId objectId = new DfId(document.getObjectId());
				try {
					IDfSysObject sysObject = (IDfSysObject) repositoryService.getSession().getObject(objectId);
					IDfClientX clientx = new DfClientX();
					IDfCheckoutOperation operation = clientx.getCheckoutOperation();
					operation.add(sysObject);
					operation.execute();
					
					document.setCheckedOut(true);
					NavigatorView view = (NavigatorView) HandlerUtil.getActivePart(event);
					view.getViewer().refresh(document);
					
					ISelectionProvider selectionProvider = HandlerUtil.getActiveSite(event).getSelectionProvider();
					UIUtils.refreshSelectionProvider(selectionProvider);
					
				} catch (DfException e) {
					throw new LimeException(e);
				}
			}
		}
		return null;
	}

}
